package indi.a709924470.emergencybutton;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RemoteViews;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmButton extends AppCompatActivity {
    public static boolean overall_activate = false;
    List<childlayout> chlt = new ArrayList<>();
    Context ctx;
    RecyclerView recv;
    public static String pkgn;
    public static boolean global_flag = false;
    public static Bitmap appIcon;
    boolean isNotified;
    public static Object nc,nt;
    public static boolean testNotify = false;
    public static boolean useAppicon = false;
    NotificationManager manager;
    @SuppressLint("HandlerLeak")
    private Handler hld = new Handler(){
        @Override
        public void handleMessage(Message msg){
            KeyguardManager mKeyguardManager = (KeyguardManager) ctx.getSystemService(Context.KEYGUARD_SERVICE);
            boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
            if((overall_activate && flag && !isNotified )|| testNotify) {
                notifies();
                System.out.println("Notified!");
                isNotified = true;
            }else if((!flag && isNotified) && !testNotify){
                isNotified = false;
                manager.cancel(1);
            }else if(!overall_activate && !testNotify){
                manager.cancel(1);
                isNotified = false;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_em_button);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(pkgn != null) {
                    Snackbar.make(view, overall_activate ? "已停止服务!" : "已启动服务!", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                    Log.d("Service", overall_activate ? "已停止服务!" : "已启动服务!");
                    overall_activate = !overall_activate;
                    changeIcon();
                }else{
                    Snackbar.make(view, "请先选择应用！", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            }
        });
        recv = (RecyclerView) findViewById(R.id.reli);
        recv.setLayoutManager(new LinearLayoutManager(this));
        List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);
        if (packages.size() == 0){
            AlertDialog.Builder ab = new AlertDialog.Builder(this);
            ab.setTitle("注意！")
                    .setMessage("你还没有给与应用读取本地应用的权限!")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    });
            AlertDialog ad = ab.create();
            ad.show();
        }
        for(int i=0;i<packages.size();i++) {
            PackageInfo packageInfo = packages.get(i);
            childlayout tmpInfo =new childlayout();
            tmpInfo.name = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
            tmpInfo.img = toBitmap(packageInfo.applicationInfo.loadIcon(getPackageManager()));
            tmpInfo.pack = packageInfo.packageName;
            chlt.add(tmpInfo);
        }
        ctx = this.getBaseContext();
        Collections.sort(chlt,new namesorter());
        recycleViewhold rvh = new recycleViewhold(chlt,ctx);
        recv.addItemDecoration(new RecyclerViewDivider(ctx,LinearLayoutManager.HORIZONTAL,1, ContextCompat.getColor(ctx, R.color.divLine)));
        recv.setAdapter(rvh);
        rvh.notifyDataSetChanged();

        EditText et = (EditText) findViewById(R.id.search);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String getk = s.toString();
                if(getk == "" || getk == " "){
                    Collections.sort(chlt,new namesorter());
                    recycleViewhold nrvh = new recycleViewhold(chlt,ctx);
                    recv.setAdapter(nrvh);
                    nrvh.notifyDataSetChanged();
                    return;
                }
                List<childlayout> lcl = new ArrayList<>();
                for (int ii = 0; ii < chlt.size(); ii++){
                    childlayout cl = chlt.get(ii);
                    if (cl.name.indexOf(getk) != -1 || cl.pack.indexOf(getk) != -1){
                        childlayout ncl = new childlayout();
                        ncl.pack = cl.pack;
                        ncl.name = cl.name;
                        ncl.img = cl.img;
                        lcl.add(ncl);
                    }
                }
                Collections.sort(lcl,new namesorter());
                recycleViewhold nrvh = new recycleViewhold(lcl,ctx);
                recv.setAdapter(nrvh);
                nrvh.notifyDataSetChanged();
            }
            @Override
            public void afterTextChanged(Editable s) {}
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message mes = hld.obtainMessage(1);
                hld.sendMessage(mes);
                hld.postDelayed(this,1000);
            }
        }).start();
    }

    public Bitmap toBitmap(Drawable dw){
        BitmapDrawable bdw = (BitmapDrawable) dw;
        return bdw.getBitmap();
    }

    public void changeIcon(){
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setImageResource(overall_activate ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play);
    }

    public String openApp() {
        String packagename = pkgn;
        PackageInfo packageinfo = null;
        try {
            packageinfo = getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return "";
        }
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);
        List<ResolveInfo> resolveinfoList = getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            String className = resolveinfo.activityInfo.name;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            return className;
        }
        return "";
    }

    public void notifies(){
        //int apiVer = android.os.Build.VERSION.SDK_INT;
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        ComponentName cn = new ComponentName(pkgn, openApp());
        intent.setComponent(cn);
        PendingIntent contentIntent = PendingIntent.getActivity
                (EmButton.this, 0, intent, 0);
        try {
            NotificationCompat.Builder nbu =
                    (NotificationCompat.Builder) new NotificationCompat.Builder(ctx).setContentTitle((nt == "" || nt == null) ? "ALERT!!!" : nt.toString())
                            .setContentText((nc == "" || nc == null) ? "Technical Nuck INCOMING!!!" : nc.toString())
                            .setAutoCancel(true)
                            .setCategory(Notification.CATEGORY_ALARM)
                            .setSmallIcon(android.R.drawable.ic_menu_view)
                            .setPriority(Notification.PRIORITY_MAX)
                            .setLargeIcon(!useAppicon ? BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher_round) : appIcon)
                            .setWhen(System.currentTimeMillis())
                            .setDefaults(Notification.COLOR_DEFAULT);
            nbu.setContentIntent(contentIntent);
            manager.notify(1,nbu.build());
        }catch (Exception exc) {
            Notification noti = new Notification(android.R.drawable.btn_star, ((nt == "" || nt == null) ? "ALERT!!!" : nt.toString()), System.currentTimeMillis());
            noti.flags = Notification.FLAG_INSISTENT;
            RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.floating_button);
            if (!useAppicon) {
                remoteView.setImageViewResource(R.id.imageView, android.R.drawable.ic_menu_view);
            }else {
                remoteView.setImageViewBitmap(R.id.imageView, appIcon);
            }
            remoteView.setTextViewText(R.id.fbtn, ((nc == "" || nc == null) ? "Technical Nuck INCOMING!!!" : nc.toString()));
            noti.contentView = remoteView;
            noti.contentIntent = contentIntent;
            manager.notify(1,noti);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_em_button, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.opensettings) {
            startActivity(new Intent(this,activity_settings.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
